package com.example.redissondemo.config;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author wuyunbin
 * 不带看门狗
 */
@Component
public class DistributedLockWithoutDog {

    private final RedissonClient redissonClient;

    @Autowired
    public DistributedLockWithoutDog(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }

    public void doSomethingWithLock() {
        // 定义锁名称，这里假设我们要锁住一个名为"myLock"的资源
        String lockName = "myLock";

        // 获取分布式锁对象
        RLock lock = redissonClient.getLock(lockName);

        try {
            // 尝试获取锁，等待时间为1秒，锁的持有时间为3秒
            boolean isLocked = lock.tryLock(1, 3, TimeUnit.SECONDS);

            if (isLocked) {
                // 成功获取到锁，执行业务逻辑
                System.out.println(Thread.currentThread().getName()+"获取锁并开始执行任务");
                // 模拟业务逻辑的执行时间5秒，这样在任务执行期间锁会被释放，会抛出异常IllegalMonitorStateException
                for (int i = 1; i <= 5; i++) {
                    Thread.sleep(1000);
                    System.out.println("任务执行了"+i+"秒");
                }
            } else {
                // 获取锁失败，可以进行相应处理，或抛出异常
                System.out.println("获取锁失败。。。");
            }
        } catch (InterruptedException e) {
            // 处理中断异常
            System.out.println("Thread interrupted while acquiring lock.");
            Thread.currentThread().interrupt();
        } finally {
            // 释放锁
            System.out.println(Thread.currentThread().getName()+"释放了锁");
            lock.unlock();
        }
    }
}
